package com.zjw.socket.demo.starter.messageService;

import java.nio.ByteBuffer;

public class MessageParser {

  public static Message fromByte(byte[] bytes) {
    ByteBuffer wrap = ByteBuffer.wrap(bytes);
    long messageId = wrap.getLong();
    long fromId = wrap.getLong();
    long toId = wrap.getLong();
    long time = wrap.getLong();
    int type = wrap.getInt();
    Message message = MessageCacheFactory.obtain();
    message.setMessageId(messageId);
    message.setFromId(fromId);
    message.setToId(toId);
    message.setTime(time);
    message.setType(type);
    if (bytes.length > 36) {
      byte[] content = new byte[bytes.length - 36];
      for (int i = 0; i < content.length; i++) {
        content[i] = wrap.get();
      }
      message.setBytes(content);
    }
    return message;
  }

  public static byte[] toByte(Message message) {
    return toByteBuffer(message).array();
  }

  public static ByteBuffer toByteBuffer(Message message) {
    byte[] content = message.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(36 + (content == null ? 0 : content.length));
    buffer.putLong(message.getMessageId());
    buffer.putLong(message.getFromId());
    buffer.putLong(message.getToId());
    buffer.putLong(message.getTime());
    buffer.putInt(message.getType());
    if (content != null) {
      buffer.put(content);
    }
    buffer.flip();
    return buffer;
  }
}
